package danny.hoi.web.controller.cargo;

import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import danny.hoi.domain.export.cargo.Contract;
import danny.hoi.domain.export.cargo.ContractExample;
import danny.hoi.domain.export.system.Dept;
import danny.hoi.domain.export.system.DeptExample;
import danny.hoi.domain.export.system.User;
import danny.hoi.service.cargo.ContractService;
import danny.hoi.service.export.system.DeptService;
import danny.hoi.web.controller.base.BaseController;
import danny.hoi.web.utils.IsParentUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
@RequestMapping("/cargo/contract")
public class ContractController extends BaseController {
    @Reference(timeout = 100000)
    private ContractService contractService;
    @Autowired
    private DeptService deptService;

    /**
     * 1.分页显示购销合同
     * 2.请求地址：/cargo/contract/list.do
     * 3.响应地址：WEB-INF/pages/cargo/contract/contract-list.jsp
     */
    @RequestMapping("/list")
    public String list(@RequestParam(defaultValue = "1") Integer pageNum,
                       @RequestParam(defaultValue = "5") Integer pageSize,
                       String key) {
        ContractExample example = new ContractExample();
        example.setOrderByClause("create_time desc");
        ContractExample.Criteria criteria = example.createCriteria();
        criteria.andCompanyIdEqualTo(getLoginCompanyId());
        /**
         * 访问权限细粒度控制
         *  Integer degree;
         * 0-saas管理员
         * 1-企业管理员
         * 2-管理所有下属部门和人员
         * 3-管理本部门
         * 4-普通员工
         */
        User user = getLoginUser();
        PageInfo<Contract> pageInfo = null;
        if (user.getDegree() == 4) {
            //普通员工只能查看自己创建的购销合同
            criteria.andCreateByEqualTo(user.getUserId());
            pageInfo = contractService.findByPages(example, pageNum, pageSize);
        } else if (user.getDegree() == 3) {
            //部门经理只能看自己部门的购销合同
            criteria.andCreateDeptEqualTo(user.getDeptId());
            pageInfo = contractService.findByPages(example, pageNum, pageSize);
        } else if (user.getDegree() == 2) {
            //部门管理员，可以查看当前部门及其子孙部门所有的购销合同
            List<String> deptIds = new ArrayList<>();

            //当前登陆的部门
            Dept loginDept = deptService.findById(user.getDeptId());
            //所在公司的所有部门
            DeptExample deptExample = new DeptExample();
            DeptExample.Criteria deptExampleCriteria = deptExample.createCriteria();
            deptExampleCriteria.andCompanyIdEqualTo(getLoginCompanyId());
            List<Dept> depts = deptService.findAll(deptExample);
            //遍历集合，找出当前部门的所有子孙部门（包括当前登陆用户的部门）
            for (Dept dept : depts) {
                if (IsParentUtils.isParent(loginDept, dept)) {
                    deptIds.add(dept.getDeptId());
                }
            }
            criteria.andCreateDeptIn(deptIds);
            pageInfo = contractService.findByPages(example, pageNum, pageSize);
        } else {
            //企业管理者，可以查看所有人的购销合同
            pageInfo = contractService.findByPages(example, pageNum, pageSize);
        }

        request.setAttribute("pageInfo", pageInfo);
        request.setAttribute("key", key);
        return "cargo/contract/contract-list";
    }

    /**
     * 1.新建
     * 2.请求地址：/cargo/contract/toAdd.do
     * 3.响应地址：WEB-INF/pages/cargo/contract/contract-add.jsp
     */
    @RequestMapping("/toAdd")
    public String toAdd() {
        return "cargo/contract/contract-add";
    }

    /**
     * 1.新建
     * 2.请求地址：/cargo/contract/toAdd.do
     * 3.响应地址：WEB-INF/pages/cargo/contract/contract-update.jsp
     */
    @RequestMapping("/toUpdate")
    public String toUpdate(String id) {
        Contract contract = contractService.findById(id);
        request.setAttribute("contract", contract);
        return "cargo/contract/contract-update";
    }

    /**
     * 1.添加/更新
     * 2.请求地址：
     * 3.响应地址：redirect /cargo/contract/list.do
     */
    @RequestMapping("/edit")
    public String edit(Contract contract) {
        contract.setCompanyId(getLoginCompanyId());
        contract.setCompanyName(getLoginCompanyName());
        contract.setUpdateTime(new Date());
        if (StringUtils.isEmpty(contract.getId())) {
            //添加
            contract.setCreateTime(new Date());
            contract.setCreateBy(getLoginUser().getUserId());
            contract.setCreateDept(getLoginUser().getDeptId());
            contractService.save(contract);
        } else {
            //更新
            contract.setUpdateBy(getLoginUser().getUserId());
            contractService.update(contract);
        }
        return "redirect:/cargo/contract/list.do";
    }

    /**
     * 1.查看
     * 2.请求地址：/cargo/contract/toView.do
     * 3.响应地址：WEB-INF/pages/cargo/contract/contract-view.jsp
     */
    @RequestMapping("/toView")
    public String toView(String id) {
        Contract contract = contractService.findById(id);
        request.setAttribute("contract", contract);
        return "cargo/contract/contract-view";
    }

    /**
     * 删除
     * 请求地址：location.href="${ctx}/cargo/contract/delete.do?id="+id;
     * 响应地址："redirect /cargo/contract/list.do";
     */
    @RequestMapping("/delete")
    public String delete(String id) {
        contractService.delete(id);
        return "redirect:/cargo/contract/list.do";
    }

    /**
     * 上报
     * 请求地址：/cargo/contract/submit.do?id="+id;
     * 响应地址："redirect /cargo/contract/list.do";
     */
    @RequestMapping("/submit")
    public String submit(String id) {
        Contract contract = new Contract();
        contract.setId(id);
        contract.setState(1);
        contractService.update(contract);
        return "redirect:/cargo/contract/list.do";
    }


    /**
     * 取消
     * 请求地址：/cargo/contract/cancel.do?id="+id;
     * 响应地址："redirect /cargo/contract/list.do";
     */
    @RequestMapping("/cancel")
    public String cancel(String id) {
        Contract contract = new Contract();
        contract.setId(id);
        contract.setState(0);
        contractService.update(contract);
        return "redirect:/cargo/contract/list.do";
    }

}
